package com.pick.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pick.admin.entity.SysMenu;
import com.pick.admin.service.SysMenuService;
import com.pick.base.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单管理控制器
 */
@Tag(name = "菜单管理")
@RestController
@RequestMapping("/system/menus")
public class SysMenuController {

    @Autowired
    private SysMenuService menuService;

    @Operation(summary = "获取菜单树")
    @SaCheckPermission("system:menu:list")
    @GetMapping("/tree")
    public Result<List<SysMenu>> getMenuTree() {
        List<SysMenu> menuTree = menuService.getMenuTree();
        return Result.success(menuTree);
    }

    @Operation(summary = "查询所有菜单")
    @SaCheckPermission("system:menu:list")
    @GetMapping("/list")
    public Result<List<SysMenu>> listMenus() {
        List<SysMenu> menus = menuService.list();
        return Result.success(menus);
    }

    @Operation(summary = "根据ID查询菜单")
    @SaCheckPermission("system:menu:query")
    @GetMapping("/{id}")
    public Result<SysMenu> getMenu(@PathVariable Long id) {
        SysMenu menu = menuService.getById(id);
        return Result.success(menu);
    }

    @Operation(summary = "创建菜单")
    @SaCheckPermission("system:menu:add")
    @PostMapping
    public Result<String> createMenu(@RequestBody SysMenu menu) {
        // 验证菜单名称是否重复
        if (menuService.isMenuNameExists(menu.getMenuName(), menu.getParentId(), null)) {
            return Result.error("同级菜单名称不能重复");
        }
        
        // 验证菜单路径是否重复
        if (menu.getMenuPath() != null && !menu.getMenuPath().trim().isEmpty()) {
            if (menuService.isMenuPathExists(menu.getMenuPath(), null)) {
                return Result.error("菜单路径不能重复");
            }
        }
        
        boolean success = menuService.createMenu(menu);
        return success ? Result.success("创建成功") : Result.error("创建失败");
    }

    @Operation(summary = "更新菜单")
    @SaCheckPermission("system:menu:edit")
    @PutMapping("/{id}")
    public Result<String> updateMenu(@PathVariable Long id, @RequestBody SysMenu menu) {
        menu.setId(id);
        // 验证菜单名称是否重复
        if (menuService.isMenuNameExists(menu.getMenuName(), menu.getParentId(), menu.getId())) {
            return Result.error("同级菜单名称不能重复");
        }
        
        // 验证菜单路径是否重复
        if (menu.getMenuPath() != null && !menu.getMenuPath().trim().isEmpty()) {
            if (menuService.isMenuPathExists(menu.getMenuPath(), menu.getId())) {
                return Result.error("菜单路径不能重复");
            }
        }
        
        boolean success = menuService.updateMenu(menu);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }

    @Operation(summary = "删除菜单")
    @SaCheckPermission("system:menu:remove")
    @DeleteMapping("/{id}")
    public Result<String> deleteMenu(@PathVariable Long id) {
        boolean success = menuService.deleteMenu(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    @Operation(summary = "获取用户菜单树")
    @GetMapping("/user/{userId}")
    public Result<List<SysMenu>> getUserMenuTree(@PathVariable Long userId) {
        List<SysMenu> menuTree = menuService.getMenuTreeByUserId(userId);
        return Result.success(menuTree);
    }

    @Operation(summary = "获取菜单选项（用于下拉选择）")
    @SaCheckPermission("system:menu:list")
    @GetMapping("/options")
    public Result<List<SysMenu>> getMenuOptions() {
        List<SysMenu> menus = menuService.list(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getStatus, 1)
                .in(SysMenu::getMenuType, 1, 2) // 只返回目录和菜单类型
                .orderByAsc(SysMenu::getSortOrder));
        return Result.success(menus);
    }

    @Operation(summary = "批量更新菜单状态")
    @SaCheckPermission("system:menu:edit")
    @PutMapping("/status")
    public Result<String> updateMenuStatus(@RequestBody List<Long> menuIds, @RequestParam Integer status) {
        boolean success = menuService.update(new LambdaUpdateWrapper<SysMenu>()
                .in(SysMenu::getId, menuIds)
                .set(SysMenu::getStatus, status));
        return success ? Result.success("状态更新成功") : Result.error("状态更新失败");
    }
}